package org.example.t0526.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Lock1 {
    public static void main(String[] args) {
        //lock默认是非公平锁，true为公平锁
        Lock lock = new ReentrantLock(false);

        new Thread(() ->{
            try{
                lock.lock();
                System.out.println("t1获得锁");
                Thread.sleep(3000);
                System.out.println("t1执行完成");
            }catch(Exception c){
                c.printStackTrace();
            }finally {
                lock.unlock();
            }

        },"t1").start();
        new Thread(() ->{
            try {
                lock.lockInterruptibly();//通过lockInterruptibly()方法获取某个锁时，如果不能获取到，只有进行等待的情况下，是可以响应中断的
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try{
                System.out.println("t2获得锁");
                Thread.sleep(3000);
                System.out.println("t2执行完成");

            }catch(Exception c){
                c.printStackTrace();
            }finally {
                lock.unlock();
            }

        },"t2").start();


//        new Thread(() ->{
//            try{
//                if(lock.tryLock(4000, TimeUnit.MILLISECONDS)){
//                    System.out.println("t2获得锁");
//                    Thread.sleep(3000);
//                    System.out.println("t2执行完成");
//                }else{
//                    System.out.println("t2获取锁失败");
//                }
//
//            }catch(Exception c){
//                c.printStackTrace();
//            }finally {
//                lock.unlock();
//            }
//
//        },"t2").start();
    }
}
